import Cocoa
import Carbon

class HotkeyManager {
    private var hotKeyRef: EventHotKeyRef?
    private var screenshotCallback: (() -> Void)?

    init() {
        setupEventHandler()
    }
    
    deinit {
        unregisterAllHotkeys()
    }
    
    func registerScreenshotHotkey(callback: @escaping () -> Void) {
        self.screenshotCallback = callback
        
        // 注册 Command + Shift + A 快捷键
        let keyCode = kVK_ANSI_A
        let flags = NSEvent.ModifierFlags([.command, .shift])
        
        registerHotKey(keyCode: keyCode, modifierFlags: flags)
    }
    
    func unregisterAllHotkeys() {
        if let ref = hotKeyRef {
            UnregisterEventHotKey(ref)
            hotKeyRef = nil
        }
    }
    
    private func setupEventHandler() {
        var eventType = EventTypeSpec()
        eventType.eventClass = OSType(kEventClassKeyboard)
        eventType.eventKind = OSType(kEventHotKeyPressed)
        
        // 安装事件处理程序
        InstallEventHandler(
            GetEventDispatcherTarget(),
            { (_, event, _) -> OSStatus in
                var hotkeyID = EventHotKeyID()
                GetEventParameter(
                    event,
                    EventParamName(kEventParamDirectObject),
                    EventParamType(typeEventHotKeyID),
                    nil,
                    MemoryLayout<EventHotKeyID>.size,
                    nil,
                    &hotkeyID
                )
                
                if hotkeyID.id == UInt32(kVK_ANSI_A) {
                    DispatchQueue.main.async {
                        if let appDelegate = NSApp.delegate as? AppDelegate {
                            appDelegate.takeScreenshot()
                        }
                    }
                }
                
                return noErr
            },
            1,
            &eventType,
            nil,
            nil
        )
    }
    
    private func registerHotKey(keyCode: Int, modifierFlags: NSEvent.ModifierFlags) {
        var gMyHotKeyID = EventHotKeyID()
        gMyHotKeyID.signature = OSType(keyCode)
        gMyHotKeyID.id = UInt32(keyCode)
        
        let modifiers = carbonFlags(from: modifierFlags)
        
        let status = RegisterEventHotKey(
            UInt32(keyCode),
            UInt32(modifiers),
            gMyHotKeyID,
            GetEventDispatcherTarget(),
            0,
            &hotKeyRef
        )

    }
    
    private func carbonFlags(from cocoaFlags: NSEvent.ModifierFlags) -> UInt32 {
        var carbonFlags: UInt32 = 0
        
        if cocoaFlags.contains(.command) {
            carbonFlags |= UInt32(cmdKey)
        }
        if cocoaFlags.contains(.shift) {
            carbonFlags |= UInt32(shiftKey)
        }
        if cocoaFlags.contains(.option) {
            carbonFlags |= UInt32(optionKey)
        }
        if cocoaFlags.contains(.control) {
            carbonFlags |= UInt32(controlKey)
        }
        
        return carbonFlags
    }
}
